package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBTools {
    protected static DruidDataSource dataSource;
    private static ThreadLocal<Connection> t=new ThreadLocal<>();

    static{
        Properties properties=new Properties();
        try {
            properties.load(DBTools.class.getClassLoader().getResourceAsStream("info.properties"));
            dataSource=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    //close

    public static Connection getConnection() {
        Connection c = t.get();
        try {
            if (c == null) {
                c = (Connection) dataSource.getConnection();
                t.set(c);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return c;
    }

    public static void startTransaction(){
        Connection connection=getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(){
        Connection connection=getConnection();
        try {
            connection.commit();
            t.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void rollback(){
        Connection connection=getConnection();
        try {
            connection.rollback();
            t.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
